package com.iot08.admin.service;

import com.iot08.admin.service.page.PageableImpl;
import com.iot08.common.entity.admin.Channel;
import com.iot08.common.entity.admin.ChannelAffiliation;
import com.iot08.common.entity.admin.SysUser;
import com.iot08.common.response.Response;
import com.iot08.common.utils.UUIDGenerator;
import com.iot08.admin.service.page.PageVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


/**
 * @version 1.0
 * @author: Rock
 * @Description: 渠道归属
 * @time: 2020/8/13 18:40
 */
@Service
public class ChannelAffiliationService {

    @Resource(name = "adminMongoTemplate")
    private MongoTemplate mongoTemplate;
    @Resource
    private ChannelService channelService;
    @Resource
    private UserService userService;
    @Resource
    private OperationService operationService;

    /**
     * @param [pageNum, pageSize]
     * @Description: 渠道归属列表
     * @time: 2020/8/14 9:40
     * @author: Rock
     * @version 1.0
     */
    public Page<ChannelAffiliation> list(PageVO page) {
        PageableImpl pageable = new PageableImpl();
        page.setSort(Sort.by(Order.desc("create_time")));
        pageable.setPage(page);

        Criteria criteria = new Criteria().and("deleted").is(0);
        if (StringUtils.isNotEmpty(page.getSearchValue())) {
            criteria.and("name").regex(".*?" + page.getSearchValue() + ".*?", "i");
        }

        Query query = new Query().addCriteria(criteria);
        long count = mongoTemplate.count(query, ChannelAffiliation.class);
        page.setTotalResult((int) count);
        List<ChannelAffiliation> list = mongoTemplate.find(query.with(pageable), ChannelAffiliation.class);
        Page<ChannelAffiliation> result = new PageImpl<ChannelAffiliation>(list, pageable, count);
        return result;
    }

    /**
     * @Description: 删除
     * @time: 2020/8/14 18:58
     * @author: Rock
     * @version 1.0
     */
    public Response<Object> updateDel(String id, SysUser user, String ip) {
        if (userService.countByChannelAffiliationId(id) > 0) {
            return Response.failedResponse("存在账号引用该渠道归属，无法删除");
        }
        Query query = new Query(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("deleted", 1);
        update.set("update_time", new Date());
        mongoTemplate.updateFirst(query, update, ChannelAffiliation.class);
        ChannelAffiliation channelAffiliation = getById(id);
        operationService.add(user, ip, "渠道归属", "删除", "删除渠道归属 ：" + channelAffiliation.getName());
        return Response.successResponse();
    }

    /**
     * @param [id]
     * @Description: 根据id查找
     * @time: 2020/8/17 18:23
     * @author: Rock
     * @version 1.0
     */
    public ChannelAffiliation getById(String id) {
        Query query = new Query(Criteria.where("_id").is(id));
        ChannelAffiliation channelAff = mongoTemplate.findOne(query, ChannelAffiliation.class);
        if (channelAff != null && channelAff.getChannelIds() != null && channelAff.getChannelIds().size() > 0) {
            List<Channel> list = channelService.getByIds(channelAff.getChannelIds());
            for (Channel c : list) {
                channelAff.getChannelCodes().add(c.getChannelCode());
            }
        }
        return channelAff;
    }

    /**
     * @Description: 保存
     * @time: 2020/8/17 17:29
     * @author: Rock
     * @version 1.0
     */
    public void save(ChannelAffiliation channelAff, SysUser user, String ip) {
        if (channelAff != null) {
            channelAff.setId(UUIDGenerator.generate());
            channelAff.setDeleted((short) 0);
            channelAff.setCreateTime(new Date());
            mongoTemplate.save(channelAff);
            operationService.add(user, ip, "渠道归属", "添加", "添加渠道归属 ：" + channelAff.getName());
        }
    }

    /**
     * @Description: 更新
     * @time: 2020/8/18 10:41
     * @author: Rock
     * @version 1.0
     */
    public void update(ChannelAffiliation channelAff, SysUser user, String ip) {
        if (channelAff != null) {
            Query query = new Query(Criteria.where("_id").is(channelAff.getId()));
            if (query != null) {
                Update update = new Update();
                update.set("name", channelAff.getName());
                update.set("desc", channelAff.getDesc());
                update.set("channel_ids", channelAff.getChannelIds());
                update.set("update_time", new Date());
                mongoTemplate.updateFirst(query, update, ChannelAffiliation.class);
                operationService.add(user, ip, "渠道归属", "编辑", "编辑渠道归属 ：" + channelAff.getName());
            }
        }
    }

    /**
     * @Description: 区别渠道归属列表
     * @time: 2020/8/20 17:35
     * @author: Rock
     * @version 1.0
     */
    public List<ChannelAffiliation> listAll() {
        return mongoTemplate.find(new Query(Criteria.where("deleted").is(0)), ChannelAffiliation.class);
    }

    /**
     * 根据渠道id获取数据
     *
     * @param [channelId]
     * @time: 2020/9/7 15:04
     * @author: Rock
     * @version 1.0
     */
    public List<ChannelAffiliation> listByChannelIds(String channelId) {
        Criteria criteria = Criteria.where("deleted").is(0);
        criteria.and("channel_ids").regex(".*?" + channelId + ".*?", "i");
        return mongoTemplate.find(new Query(criteria), ChannelAffiliation.class);
    }

    /**
     * @param [name]
     * @time: 2020/9/8 14:31
     * @author: Rock
     * @version 1.0
     */
    public ChannelAffiliation getByName(String name) {
        Query query = new Query(Criteria.where("name").is(name).and("deleted").is(0));
        return mongoTemplate.findOne(query, ChannelAffiliation.class);
    }
}
